package org.lojzes.lojzesframework.freemark;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class FreeMarkFactory {
	private static final Configuration sqlConfig = new Configuration(Configuration.VERSION_2_3_23);
	private static String ENCODING = "UTF-8";
	static{
		try {
			sqlConfig.setDirectoryForTemplateLoading(new File("templates"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 判断模板是否存在
	 * 
	 * @param path
	 * @return
	 */
	public boolean isExistTemplate(String path) {
		try {
			Template template = sqlConfig.getTemplate(path);
			return template == null ? false : true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
    /**
     * 获得可执行sql
     * @param tplName
     * @param paras
     * @return
     */
	public static String parseTemplate(String tplName, Map<String, Object> paras) {
		StringWriter stringWriter = new StringWriter();
         try {
			Template template = sqlConfig.getTemplate(tplName,ENCODING);
			template.process(paras, stringWriter);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return stringWriter.toString().trim();
	}
}
